package com.wanmait.wanmarecruit.webController;

import com.wanmait.wanmarecruit.entity.LoginLog;
import com.wanmait.wanmarecruit.entity.User;
import com.wanmait.wanmarecruit.service.LoginLogService;
import com.wanmait.wanmarecruit.service.UserService;
import com.wanmait.wanmarecruit.util.CookieUtils;
import com.wanmait.wanmarecruit.util.PasswordUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
@RequestMapping("web")
public class WebSignInController {

    @Resource
    private UserService userService;
    @Resource
    private LoginLogService loginLogService;
    @Value("${hash.algorithm-name}")
    private String hashName;
    @Value("${hash.iterations}")
    private int hashIterations;

    //修改密码
    @RequestMapping("changePassword")
    public String changePassword(User user){
        userService.changePassword(user);
        return "redirect:/web/personal/login";
    }

    //发送验证码之前，验证账是否注册
    @RequestMapping("verifySignUp")
    @ResponseBody
    public String verifySignUp(String memPhone){
        boolean flag = userService.verifySignUp(memPhone);
        return flag+"";
    }

    //登录
    @RequestMapping("signIn")
    public String signIn(User user, HttpServletRequest request, String onCook, HttpServletResponse response){
        User users = userService.signInOrNot(user);
        if(users==null){
            return "redirect:/web/personal/signIn?err=1";
        }
        HttpSession session = request.getSession();
        session.setAttribute("user",users);
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(users.getId());
        loginLog.setIp(request.getRemoteAddr());
        loginLogService.save(loginLog);
        if (onCook!=null)
        {
            String randomPass = PasswordUtils.md5(users.getPass());
            String randomPhone = PasswordUtils.randomString(2)+users.getPhone()+PasswordUtils.randomString(2);
            CookieUtils.addCookie("phone",randomPhone,"/",60*24*24*7,response);
            CookieUtils.addCookie("pass",randomPass,"/",60*24*24*7,response);
        }
        else
        {
            CookieUtils.addCookie("phone",null,"/",0,response);
            CookieUtils.addCookie("pass",null,"/",0,response);
        }
        String uri = (String)session.getAttribute("uri");
        if (uri!=null)
        {
           return "redirect:"+uri;
        }
        else {
            return "redirect:/web/personal/index";
        }
    }

    @PostMapping("/personal/tryLogin")
    public ModelAndView tryLogin(User user,String onCook,HttpServletRequest request,HttpServletResponse response)
    {
        ModelAndView modelAndView = new ModelAndView();
        User user1 = userService.LoginOrNot(user);
        if (user1==null){
            modelAndView.setViewName("redirect:/web/personal/login?err=1");
        }
        else {
            HttpSession session = request.getSession();
            session.setAttribute("user",user1);
            LoginLog loginLog = new LoginLog();
            loginLog.setUserId(user1.getId());
            loginLog.setIp(request.getRemoteAddr());
            loginLogService.save(loginLog);
            if(onCook!=null){
                String randomPass = PasswordUtils.md5(user1.getPass());
                String randomPhone = PasswordUtils.randomString(2)+user1.getPhone()+PasswordUtils.randomString(2);
                CookieUtils.addCookie("phone",randomPhone,"/",60*24*24*7,response);
                CookieUtils.addCookie("pass",randomPass,"/",60*24*24*7,response);
            }
            else {
                CookieUtils.addCookie("phone",null,"/",0,response);
                CookieUtils.addCookie("pass",null,"/",0,response);
            }
            String uri = (String)session.getAttribute("uri");
            if (uri!=null)
            {
                modelAndView.setViewName("redirect:"+uri);
            }
            else {
                modelAndView.setViewName("redirect:/web/personal/index");
            }
        }
        return modelAndView;
    }

    @RequestMapping("/personal/logout")
    public String logout(HttpSession session,HttpServletResponse response)
    {
        session.removeAttribute("user");
        CookieUtils.addCookie("phone",null,"/",0,response);
        CookieUtils.addCookie("pass",null,"/",0,response);
        return "redirect:/web/personal/signIn";
    }

    @PostMapping("/personal/changePassword")
    public String changePassWord(HttpSession session,String pass)
    {
        String salt = UUID.randomUUID().toString().replaceAll("-","");
        pass = new SimpleHash(hashName,pass,salt,hashIterations).toString();
        userService.updateById(new User().setId(((User)session.getAttribute("user")).getId()).setPass(pass).setSalt(salt));
        return "redirect:/web/personal/logout";
    }

    @GetMapping("/personal/checkOldPass")
    @ResponseBody
    public String checkOldPass(String password,HttpSession session)
    {
        Integer id = ((User)session.getAttribute("user")).getId();
        return userService.checkPass(new User().setId(id).setPass(password))+"";
    }

    @GetMapping("/personal/getPhoneNum")
    @ResponseBody
    public String getPhoneNum(Integer userId)
    {
        User user = userService.getById(userId);
        return user.getPhone();
    }
}
